package serv_cmd

import (
	"fmt"
	"net"

	"atomgit.com/openlinksaas/proto-gen-go.git/swarm_proxy_api"
	"atomgit.com/openlinksaas/swarm_api_proxy/config"
	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
	grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
	"github.com/spf13/cobra"
	"google.golang.org/grpc"
)

var cfgPath *string

var servCmd = &cobra.Command{
	Use:  "serv",
	RunE: runServ,
}

func Init(cfg *string, rootCmd *cobra.Command) {
	cfgPath = cfg
	rootCmd.AddCommand(servCmd)
}

func runServ(cmd *cobra.Command, args []string) error {
	if cfgPath == nil {
		return fmt.Errorf("miss config")
	}
	cfg, err := config.LoadProxyConfig(*cfgPath)
	if err != nil {
		return err
	}
	grpcServer := grpc.NewServer(grpc.StreamInterceptor(
		grpc_middleware.ChainStreamServer(
			grpc_recovery.StreamServerInterceptor(),
		)),
		grpc.UnaryInterceptor(
			grpc_middleware.ChainUnaryServer(
				grpc_recovery.UnaryServerInterceptor(),
			)),
	)
	swarm_proxy_api.RegisterSwarmProxyApiServer(grpcServer, newSwarmProxyApiImpl(cfg))
	addr, err := net.ResolveTCPAddr("tcp4", cfg.ListenAddr)
	if err != nil {
		return err
	}
	li, err := net.ListenTCP("tcp4", addr)
	if err != nil {
		return err
	}
	err = grpcServer.Serve(li)
	return err
}
